<?php
/**
 * @author seirios-ls
 * 2021/6/7
 */

namespace BreakCode\BaseInterface;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;

class Connector
{
    /**
     * 自动赋予变量
     * @param array $options
     */
    public function setOptions(array $options = [])
    {
        $vars = get_class_vars(get_class($this));

        $options = array_intersect_key($options, $vars);

        foreach ($options as $option => $value) {
            $this->$option = trim($value);
        }
    }

    /**
     * 请求
     * @param string $url
     * @param array $param
     * @param string $method
     * @param array $header
     * @return Response
     * @throws GuzzleException
     */
    protected function request(string $url, string $method = 'GET', array $param = [], array $header = []): Response
    {
        $method = strtolower($method);
        if ($method == 'get' and $param) {
            $url .= '?' . http_build_query($param);
        }

        $options = $this->buildRequestOptions($param, $method, $header);

        $client = new Client();

        $response = $client->request($method, $url, $options);

        return Response::generate($response->getStatusCode(), $response->getBody(), $response->getHeaders());
    }

    /**
     * 单例请求
     * @throws GuzzleException
     */
    protected function requestOne(Response $requestOne, string $url, string $method = 'GET', array $param = [], array $header = []): Response
    {
        $method = strtolower($method);
        if ($method == 'get' and $param) {
            $url .= '?' . http_build_query($param);
        }

        $options = $this->buildRequestOptions($param, $method, $header);

        $client = new Client();

        $response = $client->request($method, $url, $options);

        $requestOne->setCode($response->getStatusCode())
            ->setBody($response->getBody())
            ->setHeader($response->getHeaders());

        return $requestOne;
    }

    private function buildRequestOptions(array $param = [], string $method = 'GET', array $header = []): array
    {
        $options = [];

        if ($header) {
            $options['headers'] = $options;
        }
        if ($param) {
            $options['form_params'] = $param;
        }

        return $options;
    }
}